<template>
  <div class="index" :class="{'index-bottom': fadeIn}" v-show="showWholePage">
    <Carousel :text="scrollText" :goldenNotice="true" bgColor="#fff" color="#777"></Carousel>
    <div class="index-header">
      <div class="index-logo">
        <img src="../../assets/img/index-logo.png" alt="">
      </div>
      <NextVote :timeType="timeType" ref="nextVote"></NextVote>
      <h1 class="index-title" :style="{'font-size':titleFontSize}">{{year}}年中国{{catName}}十大品牌排行</h1>
      <form class="index-search" @submit.prevent="onSearch">
        <input type="search" placeholder="快速搜索本页面品牌" v-model="keyword" @input="onSearch" @focus="onMenuShow" @blur="onMenuHide">
        <span class="search-icon"></span>
      </form>
    </div>
    <Tab :tabtitles="tabs" :slidable="false" :animate="false" @tab-change-start="onTab" className="index-tab" ref="tab">
      <div class="tab-container" v-show="currentTab===1">
        <transition name="fade">
          <ul class="vote-list" key="1">
            <li v-for="item in brandList" :key="item.id">
              <VoteItem :shortName="item.title" :img="item.thumb" :ranking="item.ranking" :votes="item.vote_count" :status="status" :itemid="item.itemid" @vote="onVoteClick(item)" @apply="onApplyClick(item)" @click.native="gotoDetail(item)"></VoteItem>
            </li>
          </ul>
        </transition>
      </div>
      <div class="tab-container" v-show="currentTab===2">
        <transition name="fade">
          <div key="2">
            <div class="index-divide-line">
              <img src="../../assets/img/divide-line.png" alt="">
            </div>
            <InfoItem v-for="(item,index) in catInfo.jieshao" :key="index" :title="item.Title" :content="item.Content" :img="item.Thumb"></InfoItem>
          </div>
        </transition>
      </div>
      <div class="tab-container" v-show="currentTab===3">
        <transition name="fade">
          <div key="3">
            <div class="index-divide-line">
              <img src="../../assets/img/divide-line.png" alt="">
            </div>
            <InfoItem v-for="(item,index) in catInfo.xuangou" :key="index" :title="item.Title" :content="item.Content" :img="item.Thumb"></InfoItem>
          </div>
        </transition>
      </div>
      <div class="tab-container" v-show="currentTab===4">
        <transition name="fade">
          <div key="4">
            <div class="index-divide-line">
              <img src="../../assets/img/divide-line.png" alt="">
            </div>
            <h2 class="detail-title">一.规则介绍：</h2>
            <div class="rule-item clearfix">
              <span class="rule-name">开始时间：</span>
              <p class="rule-content">{{catInfo.startDate}}</p>
            </div>
            <div class="rule-item clearfix">
              <span class="rule-name">结束时间：</span>
              <p class="rule-content">{{catInfo.endDate}}</p>
            </div>
            <div class="rule-item clearfix">
              <span>投票规则：</span>
              <p class="rule-dot" v-for="(item,index) in catInfo.vote_rule" :key="index+'1'">{{item}}</p>
            </div>
            <div class="rule-item clearfix">
              <span>品牌荣誉：</span>
              <p class="rule-dot" v-for="(item,index) in catInfo.brand_honor" :key="index+'2'">{{item}}</p>
            </div>
            <h2 class="detail-title">二.活动介绍：</h2>
            <p class="detail-content" v-for="(item,index) in catInfo.introduce" :key="index+'3'">{{item}}</p>
            <h2 class="detail-title">三.严禁刷票公告：</h2>
            <p class="detail-content" v-for="(item,index) in catInfo.notice" :key="index+'4'">{{item}}</p>
          </div>
        </transition>
      </div>
    </Tab>
    <MyFooter :tel="tel"></MyFooter>
    <div class="btn-round" :class="{'menu-top-move': isShowToend}" v-show="currentTab!==1&&isPhoneWx" @click="onBackToVote">
      返回<br>投票
    </div>
    <div class="show-menu" @click="onShowMenu" :class="{'menu-top-move': isShowToend}" v-if="isPhoneWx" v-show="cursorMenuShow && showMenuBtn && currentTab == 1">
      <img src="../../assets/img/menu-btn.png" alt="">
    </div>
    <div class="recomand-brand-icon btn-round" :class="{'recomand-top-move': isGuideshow}" @click="onAddBrand" v-if="!isPhoneWx  && currentTab == 1">
      品牌<br>推荐
    </div>
    <div class="wake-up-app-btn" @click="onWakeUpApp" v-if="!isWeiXin&&isPhone"></div>
    <div class="to-end-bg" :class="{'fadeIn': fadeIn}" v-if="isPhoneWx && status===2" @click="goToEnd" v-show="cursorMenuShow"></div>
    <div v-if="animationHide">
      <FallingDownAnimation @clear="onHide" @onShowBtn="onShowBtn"></FallingDownAnimation>
    </div>
    <VoteMenu v-if="showMenu" @closeMenu="onCloseMenu" :cstatus="status"></VoteMenu>
    <Vote ref="vote" @voted="onVoted"></Vote>
    <GuidePage @guideshow="onGuideshow"></GuidePage>
    <transition name="fade">
      <div class="not-wx-tip-box" v-if="showNotWxTip" @click="closeNotWx">
        <div class="img-box zoom-in animated">
          <img :src="notWXQrcodeImg" alt="">
        </div>
        <div class="img-box zoom-in animated" v-if="isPhone">
          <img src="./assets/not-wx-img.png" alt="">
        </div>
        <div class="not-wx-close">
          <img src="../../assets/img/close-btn.png" alt="">
        </div>
      </div>
    </transition>
    <div class="bottom-btn home-btn" @click="onHome" v-show="showHomeBtn&&currentTab===1&&isWeiXin">
      <img src="./assets/home.png" alt="">
      <span>首页</span>
    </div>
    <div class="bottom-btn refresh-btn" @click="onRefresh" v-show="showRefreshBtn&&currentTab===1&&status===1">
      <img src="./assets/refresh.png" alt="">
      <span>刷新</span>
    </div>
  </div>
</template>

<script>
import Carousel from '../../components/Carousel'
import Tab from '../../components/VueTab'
import MyFooter from '../../components/MyFooter'
import VoteItem from './components/VoteItem'
import * as events from '../../store/events'
import InfoItem from './components/InfoItem'
import VoteMenu from '../../components/VoteMenu'
import scroll from '../../mixins/scroll'
import setTitle from '../../common/setTitle'
import Vote from './components/Vote'
import GuidePage from '../../components/GuidePage'
import consts from '../../common/consts'
import NextVote from './components/NextVote'
import FallingDownAnimation from '../../components/FallingDownAnimation'
import * as auth from '../../common/auth'
import { mapState } from 'vuex'
import * as utils from '../../common/utils'
import getDeviceInfo from '../../common/deviceInfo'
import "../../common/php"

let refreshInterval = 0
let canRefresh = true
let notWxShareLink
export default {
  mixins: [scroll],
  components: {
    Carousel,
    Tab,
    MyFooter,
    VoteItem,
    InfoItem,
    VoteMenu,
    Vote,
    NextVote,
    GuidePage,
    FallingDownAnimation
  },
  data() {
    return {
      catid: '',
      keyword: '',
      currentTab: 1,
      year: '',
      tabs: ['行业投票', '行业介绍', '选购课堂', '活动详情'],
      scrollText: '',
      catName: '', // 行业名称
      tel: '',
      allBrandList: [],
      brandList: [],
      catInfo: {}, // 行业数据
      showMenu: false, // 是否显示首页菜单
      isWeiXin: false, // 是否是微信浏览器
      isPhone: false, // 是否是手机端
      isPhoneWx: false, // 是否是手机端微信
      captchaType: 0, // 投票验证码类型
      timeType: 0, // 投票时间间隔类型
      // 非微信打开 提示页面
      showNotWxTip: false,
      notWXQrcodeImg: '',
      // 是否显示返回首页按钮
      showHomeBtn: false,
      // 是否显示刷新按钮
      showRefreshBtn: false,
      // 控制整页是否显示 防止来回跳页时候屏幕闪动
      showWholePage: false,
      cursorMenuShow: true, // 获取焦点时 控制菜单按钮
      showMenuBtn: true, // 控制菜单按钮
      isGuideshow: false, // 添加品牌按钮位置
      animationHide: false, // 控制飘落动画
      onceAnimation: false, // 显示一次动画
      fadeIn: false // 显示跳转揭榜页按钮
    }
  },
  computed: {
    titleFontSize() {
      let fz = 42
      if (this.catName.length < 5) {
        fz = 42
      } else if (this.catName.length <= 12) {
        fz = -2 * this.catName.length + 51
      } else {
        fz = 28
      }
      return fz / 100 + 'rem'
    },
    ...mapState({
      status: s => s.categoryStatus,
      downloadLink: s => s.appDownloadLink,
      pageSwitch: s => s.pageSwitch,
      addBrandBtn: s => s.addBrandBtn
    }),
    isShowToend() {
      if (this.status === 2 && this.isPhoneWx && this.fadeIn) return true
    }
  },
  beforeRouteEnter(to, from, next) {
    next()
    if (from.name && from.name !== 'index' && from.name !== 'addbrand' && from.name !== 'noWechatPage' && !getDeviceInfo().isWeiXin) {
      window.location.reload()
    }
  },
  created() {
    this.isWeiXin = this.$getDeviceInfo().isWeiXin
    this.isPhone = this.$getDeviceInfo().isPhone
    this.isPhoneWx = this.$getDeviceInfo().isWeiXin && this.$getDeviceInfo().isPhone
    this.onceAnimation = window.sessionStorage.getItem('onceAnimation')
    if (this.onceAnimation) {
      this.fadeIn = true
    }
    if (!this.isWeiXin && !this.isPhone) {
      this.isGuideshow = true
    }
    // 进入首页做个标记
    window.sessionStorage.setItem('fromIndex', true)
  },
  mounted() {
    let originalHeight = document.documentElement.clientHeight || document.body.clientHeight
    window.addEventListener("resize", () => {
      //键盘弹起与隐藏都会引起窗口的高度发生变化
      let resizeHeight = document.documentElement.clientHeight || document.body.clientHeight
      if (resizeHeight - 0 < originalHeight - 0) {
        //当软键盘弹起，在此处操作
        if (this.$getDeviceInfo().isPhone) {
          this.cursorMenuShow = false
        }
      } else {
        //当软键盘收起，在此处操作
        if (this.$getDeviceInfo().isPhone) {
          this.cursorMenuShow = true
        }
      }
    })
    this.$showLoading()
    this.catid = this.$route.query.catid || this.$route.params.catid
    this.$store.commit(events.SET_CAT_ID, this.catid)
    // 登录
    auth.login(this.$route).then(() => {
      // 检查是否被封号
      auth.check(this.$route).then(() => {
        this.getStatus() // 获取当前行业投票状态
      }).catch((msg) => {
        this.$hideLoading()
        if (msg) {
          this.$toast.center(msg)
        }
      })
    }).catch(() => { })
  },
  methods: {
    // 获取当前行业投票状态
    getStatus() {
      if (!this.status) {
        this.$api.getCategoryStatus(this.catid).then(data => {
          this.$store.commit(events.SET_CATE_STATUS, parseInt(data.data.category_status || data.data.status))
          this.$store.commit(events.SET_PAGE_SWITCH, parseInt(data.data.page_switch))
          this.gotStatus(this.status)
          // 错误链接二维码
          if (data.data.wechatqr) {
            this.$store.commit(events.SET_ERROR_WX_QRCODE, data.data.wechatqr)
          }
          // 错误链接QQ
          if (data.data.qq) {
            this.$store.commit(events.SET_ERROR_QQ, data.data.qq)
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        this.gotStatus(this.status)
      }
    },
    gotStatus(status) {
      if (status === 40002) { // catid不正确 跳转到该页面
        this.$router.replace('/catidNotRightPage')
        return
      } else if (status === 5) {
        if (this.isWeiXin && this.isPhone) {
          // 如果是ios端 以刷新页面的方式进入 不然分享配置不生效
          window.sessionStorage.setItem('replaced', true)
          if (this.pageSwitch === 1) {
            this.$router.replace('/newEndPage?catid=' + this.catid)
          }
          if (this.pageSwitch === 0) {
            this.$router.replace('/oldEndPage?catid=' + this.catid)
          }
        } else {
          this.showWholePage = true
          this.getList()
        }
        return
      } else {
        this.showWholePage = true
        this.getList()
      }
    },
    effectShow(e) {
    },
    // 获取品牌列表
    getList() {
      this.$api.getBrandList(this.catid).then(data => {
        this.$hideLoading()
        if (parseInt(data.data.status) === 1) { // 请求成功
          // 揭榜三天内 动画判断
          if (this.status === 2 && this.isPhoneWx && !this.fadeIn) {
            this.animationHide = true
            // 每次进入只显示一次动画
            window.sessionStorage.setItem('onceAnimation', true)
          }
          if (this.status === 5) {
            if (data.data.brandList.length > 10) {
              this.brandList = data.data.brandList.slice(0, 10)
            } else {
              this.brandList = data.data.brandList
            }
          } else {
            // 品牌列表
            this.brandList = data.data.brandList
          }
          this.allBrandList = this.brandList
          // 解决ios回退白屏的问题，勿删
          window.scrollTo(0, 1)
          window.scrollTo(0, 0)

          // 行业数据
          this.catInfo = data.data.catinfo
          // 验证码类型
          this.captchaType = parseInt(this.catInfo.captcha)
          // 投票时间间隔类型
          this.timeType = parseInt(this.catInfo.timetype)
          // 跑马灯数据
          if (this.catInfo.rolling_text) {
            this.scrollText = this.catInfo.rolling_text.join(' ')
          }
          //年份
          this.year = data.data.year
          // 标题
          this.catName = this.catInfo.catname || ''
          setTitle(this.year + '年中国' + this.catName + '十大品牌排行')
          // catname存到store中
          this.$store.commit(events.SET_CAT_NAME, this.catName)
          // 电话
          this.tel = this.catInfo.service_tel
          // 客服数据
          let service = {
            qq: this.catInfo.qq, // 客服qq号码
            wxqr: this.catInfo.wechatqr, // 客服微信二维码
            tel: this.catInfo.service_tel   // 客服电话
          }
          // 客服数据存到store中
          this.$store.commit(events.SET_SERVICE_INFO, service)
          // 小程序码存到store中AppletLink
          if (data.data.share_xcx_ewm_link) {
            this.$store.commit(events.SET_WX_APPLET_LINK, data.data.share_xcx_ewm_link)
          }
          // 纯小程序码存到store中AppletLink
          if (data.data.xcx_ewm_link) {
            this.$store.commit(events.SET_WX_XCX_LINK, data.data.xcx_ewm_link)
          }
          // pc投票链接二维码存到store中voteLink
          if (data.data.vote_ewm_link) {
            this.$store.commit(events.SET_PC_VOTE_LINK, data.data.vote_ewm_link)
          }
          // pc引导图存到store中voteLink
          if (data.data.yindao_share_ewm_link) {
            this.$store.commit(events.SET_GUIDE_LINK, data.data.yindao_share_ewm_link)
          }
          // 把app下载链接存到store中
          this.$store.commit(events.SET_DOWNLOAD_LINK, data.data.app_download_link)
          // 微信二维码存到store中
          this.$store.commit(events.SET_WX_VOTE_LINK, data.data.share_ewm_link)
          // pc端左侧二维码数组存到store中
          this.$store.commit(events.SET_QRCODE_LIST, data.data.left_ewm_arr)
          // 非微信端点击投票提示图片链接
          notWxShareLink = data.data.share_ewm_link
          if (!(this.$getDeviceInfo().isWeiXin && this.$getDeviceInfo().isPhone)) {
            this.getNotWxQrcode()
          }
          // 是否显示返回首页按钮
          this.showHomeBtn = parseInt(data.data.openHomePage)
          // 是否显示刷新按钮
          this.showRefreshBtn = parseInt(data.data.refreshButton)
          refreshInterval = data.data.refreshInterval
          // 更新显示下次投票时间
          this.$nextTick(() => {
            this.$refs.nextVote.update()
          })
          // 尝试启动app
          if (!this.isWeiXin) {
            utils.openApp(this.catid, this.catName, this.status, '', this.pageSwitch)
          }
        }
      }).catch(err => {
        console.log(err)
        this.$toast.center('网络请求出错')
        this.$hideLoading()
      })
    },
    // 确定搜索
    onSearch() {
      if (!this.keyword) {
        this.brandList = this.allBrandList
        return
      }
      this.brandList = this.allBrandList.filter(item => {
        return item.title.indexOf(this.keyword) != -1
      })
    },
    onMenuShow() {
      if (this.$getDeviceInfo().isPhone) {
        this.cursorMenuShow = false
      }
    },
    onMenuHide() {
      if (this.$getDeviceInfo().isPhone) {
        this.cursorMenuShow = true
      }
    },
    //  点击立即投票按钮 
    onVoteClick(item) {
      if (this.$getDeviceInfo().isWeiXin && this.$getDeviceInfo().isPhone) {
        this.$refs.vote.acceptVoteData(item, {
          captchaType: this.captchaType,
          catid: this.catid,
          catName: this.catName,
          timeType: this.timeType
        })
      } else {
        this.openNotWx()
      }
    },
    onApplyClick(item) {
      if (this.$getDeviceInfo().isWeiXin && this.$getDeviceInfo().isPhone) {
        let catid = this.$route.query.catid || this.$route.params.catid
        this.$router.push('/applyReward/' + item.itemid + '?catid=' + catid)
      } else {
        this.openNotWx()
      }
    },
    // tab 切换回调事件
    onTab(index) {
      this.currentTab = index
    },
    // 返回投票
    onBackToVote() {
      window.scrollTo(0, 0)
      this.$refs.tab.setPage(1)
    },
    // 显示菜单
    onShowMenu() {
      this.showMenu = true
      this.scroll(false)
      this.showMenuBtn = false
    },
    // 关闭弹出菜单
    onCloseMenu() {
      this.showMenu = false
      this.scroll(true)
      this.showMenuBtn = true
    },
    // 非微信 进入添加品牌
    onAddBrand() {
      this.$router.push('/addbrand?catid=' + this.catid + '&from=index&formPath=' + this.$route.path)
    },
    onVoted() {
      // 重新获取排行列表
      this.getList()
    },
    // 进入详情页
    gotoDetail(item) {
      // if (this.$getDeviceInfo().isWeiXin) {
      this.$router.push(
        '/companyDetails/' + item.itemid + '/?catid=' + this.catid
      )
      // }
    },
    // 获取非微信打开的二维码图片
    getNotWxQrcode() {
      this.notWXQrcodeImg = notWxShareLink
    },
    openNotWx() {
      this.showNotWxTip = true
      this.scroll(false)
    },
    closeNotWx() {
      this.showNotWxTip = false
      this.scroll(true)
    },
    onHome() {
      this.$router.push('/homepage?catid=' + this.$route.query.catid)
    },
    onRefresh() {
      if (canRefresh) {
        canRefresh = false
        setTimeout(() => {
          canRefresh = true
        }, refreshInterval * 1000)
        this.$showLoading()
        this.getList()
      } else {
        this.$toast.center('刷新太频繁了，请稍后再试')
      }
    },
    goToEnd() {
      if (this.pageSwitch === 1) {
        this.$router.push('/newEndPage?catid=' + this.catid + '&pageform=index')
      }
      if (this.pageSwitch === 0) {
        this.$router.push('/oldEndPage?catid=' + this.catid + '&pageform=index')
      }
    },
    onGuideshow(e) {
      this.isGuideshow = e
    },
    onHide() { // 清除动画层
      this.animationHide = false
    },
    onShowBtn() { // 显示跳转到揭榜页按钮
      this.fadeIn = true
    },
    onWakeUpApp() {
      // 尝试启动app
      if (!this.isWeiXin) {
        utils.openApp(this.catid, this.catName, this.status, this.downloadLink, this.pageSwitch)
      }
    }
  },
  destroyed() {
    setTitle('品牌中网')
    window.removeEventListener('resize', () => { })
  }
}
</script>
<style lang="scss">
.index {
  .index-tab {
    margin-top: -1.2rem;
    .tab-title {
      font-size: 0.28rem;
      color: #fff;
      &.active,
      &:active {
        font-weight: 700;
        background-color: transparent;
        span {
          position: absolute;
          width: 1.1rem;
          height: 0.06rem;
          background-color: #fff;
          bottom: 0;
          left: 50%;
          transform: translate3d(-0.55rem, 0, 0);
        }
      }
    }
    .tab-container {
      margin-top: 0.08rem;
      background-color: #f6f6f6;
      border-radius: 0.2rem 0.2rem 0 0;
      padding-bottom: 0.3rem;
    }
  }
}
</style>

<style scoped lang="scss">
.index {
  .index-header {
    width: 100%;
    background: url("http://img.brandzw.com/skin/default/images/banner_tp.png")
      center no-repeat;
    background-size: cover;
    padding: 0.3rem 0.3rem 1.2rem 0.3rem;
    position: relative;
  }
  .index-logo {
    img {
      width: auto;
      height: 0.6rem;
    }
  }
  .index-title {
    margin-top: 0.35rem;
    color: #fff;
    font-size: 0.42rem;
  }
  .index-search {
    width: 100%;
    height: 0.76rem;
    line-height: 0.76rem;
    position: relative;
    margin-top: 0.35rem;
    input {
      width: 100%;
      height: 100%;
      background-color: #fff;
      padding-left: 0.88rem;
      font-size: 0.28rem;
      border-radius: 0.04rem;
    }
    span {
      display: inline-block;
      width: 0.28rem;
      height: 0.28rem;
      background: url(../../assets/img/search-icon.png) center no-repeat;
      background-size: contain;
      position: absolute;
      top: 0.25rem;
      left: 0.3rem;
    }
  }
  .vote-list {
    padding-top: 0.3rem;
  }
  .index-divide-line {
    width: 5.9rem;
    margin: auto;
    padding-top: 0.6rem;
    img {
      width: 100%;
      height: auto;
    }
  }
  .detail-title {
    width: 6.5rem;
    margin: 0.5rem auto 0.4rem auto;
    font-size: 0.3rem;
    color: #333;
  }
  .rule-item {
    width: 6.5rem;
    margin: 0 auto 0.3rem auto;
    font-size: 0.26rem;
    color: #999;
    .rule-name {
      width: 1.5rem;
      float: left;
    }
    .rule-content {
      color: #666;
      margin-left: 1.6rem;
      line-height: 0.4rem;
    }
    .rule-dot {
      margin-left: 0.46rem;
      margin-top: 0.2rem;
      line-height: 0.4rem;
      color: #666;
      &::before {
        content: "";
        display: inline-block;
        width: 0.12rem;
        height: 0.12rem;
        background: #ccb487;
        border-radius: 50%;
        margin-right: 0.14rem;
        vertical-align: middle;
      }
    }
  }
  .detail-content {
    font-size: 0.28rem;
    color: #666;
    width: 6.15rem;
    margin: 0 auto;
    line-height: 0.46rem;
    text-indent: 2em;
  }
  .recomand-brand-icon {
    left: 50%;
    bottom: 0.45rem;
    transform: translate3d(-0.44rem, 0, 0);
    position: fixed;
    cursor: pointer;
  }
  .recomand-top-move {
    bottom: 355px;
  }
  .menu-top-move {
    bottom: 2.8rem;
    transition: bottom 2.5s ease-in-out;
  }
}
.index-bottom {
  padding-bottom: 1rem;
}
.to-end-bg {
  width: 100%;
  height: 2.35rem;
  background: url("./assets/to-end-bg.png") center no-repeat;
  background-size: cover;
  position: fixed;
  bottom: -2.35rem;
  left: 0;
  right: 0;
  z-index: 1;
  opacity: 0;
}
.wake-up-app-btn {
  width: 1.2rem;
  height: 1.37rem;
  background: url("./assets/wake-up-app.png") center no-repeat;
  background-size: contain;
  position: fixed;
  bottom: 0.35rem;
  right: 0;
}
.not-wx-tip-box {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  z-index: 2;
  .img-box {
    width: 6rem;
    margin: 0.5rem auto 0 auto;
    img {
      width: 100%;
      height: auto;
    }
  }
  .not-wx-close {
    margin-top: 0.8rem;
    text-align: center;
    img {
      width: 0.32rem;
      height: auto;
    }
  }
}
.fadeIn {
  bottom: 0;
  opacity: 1;
  transition: opacity 2.5s ease-in-out, bottom 2.5s ease-in-out;
}
</style>
